package com.applcn.shop.service;

import cn.hutool.core.collection.CollectionUtil;
import com.applcn.core.base.Result;
import com.applcn.shop.dto.CategoryListDTO;
import com.applcn.shop.repo.entity.CategoryEntity;
import com.applcn.shop.repo.repository.CategoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * com.applcn.shop.service
 * Description:
 *
 * @author: 大妖怪
 * @date: 2020-03-26 00:18
 */
@Service
@RequiredArgsConstructor
public class CategoryService {

    private final CategoryRepository categoryRepository;

    /**
     * 查询类目列表
     *
     * @param parentId
     * @return
     */
    public Result categoryList(Long parentId) {
        return Result.ok().putData(getCategoryList(parentId));
    }

    /**
     * 递归变量类目
     *
     * @param parentId
     * @return
     */
    private List<CategoryListDTO> getCategoryList(Long parentId) {
        List<CategoryEntity> categoryEntityList = categoryRepository.getCategoryList(parentId);
        List<CategoryListDTO> categoryListDTOList = new ArrayList<>();
        for (CategoryEntity categoryEntity : categoryEntityList) {
            CategoryListDTO categoryListDTO = new CategoryListDTO();
            categoryListDTO.setValue(categoryEntity.getId());
            categoryListDTO.setLabel(categoryEntity.getName());
            List<CategoryListDTO> children = getCategoryList(categoryEntity.getId());
            if (CollectionUtil.isNotEmpty(children)) {
                categoryListDTO.setChildren(children);
            }
            categoryListDTOList.add(categoryListDTO);
        }

        return categoryListDTOList;
    }
}
